package com.cskt.securityproject.filter;

import com.cskt.securityproject.controller.ValidateCodeController;
import com.cskt.securityproject.exception.ValidateCodeException;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @description 自定义验证码过滤器
 * @date 2023/12/18 13:43
 * @auth mo
 */
@Component
public class ValidateCodeFilter extends OncePerRequestFilter {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException,IOException {
    //    判断当前请求路径是否为login ,只有登录才需要验证验证码
        String requestURI = request.getRequestURI();
        if (!requestURI.equals("/login")) {
            //当前请求不是登录，直接放行
            filterChain.doFilter(request, response);
            return;
        }
        //先生成验证码的key ,必须与生成验证码存储到redis中的保持一致
        String remoteAddr = request.getRemoteAddr();
        String validateKey = ValidateCodeController.REDIS_KEY_IMAGE_CODE + "-" + remoteAddr;
    //    从redis中取出验证码
        String validateCode = stringRedisTemplate.opsForValue().get(validateKey);
    //    从request中取出前端传递过来的验证码参数
        String imageCode = request.getParameter("imageCode");
        if (!StringUtils.hasText(imageCode)) {
            throw new ValidateCodeException("验证码不能为空");
        }
        if (!StringUtils.hasText(validateCode)) {
            throw new ValidateCodeException("验证码已过期");
        }
        if (!imageCode.equals(validateCode)) {
            throw new ValidateCodeException("验证码错误");
        }

    //    验证通过后放行并直接删除redis中的验证码
        filterChain.doFilter(request,response);
        stringRedisTemplate.delete(validateKey);
    }
}
